package top.mingyi4cjh.cms.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.mingyi4cjh.cms.dao.ApprovalDao;
import top.mingyi4cjh.cms.dao.ArticleApprovalDOMapper;
import top.mingyi4cjh.cms.dao.ArticleDao;
import top.mingyi4cjh.cms.dao.UserIdentifyDao;
import top.mingyi4cjh.cms.dataobject.ArticleApprovalDO;
import top.mingyi4cjh.cms.dataobject.ArticleDO;
import top.mingyi4cjh.cms.model.ArticleModel;
import top.mingyi4cjh.cms.service.ArticleService;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MingYi
 * @program cms
 * @create 2022/04/30 18:22
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Resource
    private ArticleDao articleDao;

    @Resource
    private ApprovalDao approvalDao;

    @Resource
    private UserIdentifyDao userIdentifyDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createArticle(ArticleModel articleModel) {
        ArticleDO articleDO = convertDoFromModel(articleModel);
        articleDao.insert(articleDO);
        approvalDao.insert(articleModel.getArticleId());
    }

    @Override
    public void deleteArticle(Long articleId) {
        articleDao.deleteByArticleId(articleId);
    }

    @Override
    public ArticleModel getArticle(Long articleId) {
        ArticleDO result = articleDao.selectByArticleId(articleId);
        return convertModelFromDo(result);
    }

    @Override
    public List<ArticleModel> getSelfList(Long authorId) {
        List<ArticleDO> result = articleDao.selectByAuthorId(authorId);
        return result.stream().map(this::convertModelFromDo).collect(Collectors.toList());
    }

    @Override
    public boolean isArticleOwner(Long userId, Long articleId) {
        ArticleDO articleDO = articleDao.selectByArticleId(articleId);
        return userId.equals(articleDO.getAuthorId());
    }

    @Override
    public int queryIdentify(Long userId) {
        return userIdentifyDao.queryUserIdentify(userId);
    }

    @Override
    public void approval(Long articleId, Integer status, Long userId) {
        approvalDao.update(articleId, status, userId);
    }

    @Override
    public List<ArticleApprovalDO> getNotApprovalList() {
        return approvalDao.getNotApprovalList();
    }

    private ArticleDO convertDoFromModel(ArticleModel articleModel) {
        if (articleModel == null) {
            return null;
        }
        ArticleDO articleDO = new ArticleDO();
        BeanUtils.copyProperties(articleModel, articleDO);
        return articleDO;
    }


    private ArticleModel convertModelFromDo(ArticleDO articleDO) {
        if (articleDO == null) {
            return null;
        }

        ArticleModel articleModel = new ArticleModel();
        BeanUtils.copyProperties(articleDO, articleModel);
        return articleModel;
    }
}
